package com.yyy.tcc.service.compensation;

import com.yyy.common.exception.BusinessException;
import com.yyy.tcc.entity.TransferRecord;
import com.yyy.tcc.service.AccountService;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.*;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.listener.KafkaMessageListenerContainer;
import org.springframework.kafka.listener.MessageListener;

import javax.sql.DataSource;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 基于Kafka的事务补偿服务
 */
public class KafkaCompensationService {
    private static final Logger log = LoggerFactory.getLogger(KafkaCompensationService.class);
    private static final String TOPIC = "transaction-compensation";

    private final DataSource dataSource;
    private final KafkaTemplate<String, String> kafkaTemplate;
    private final KafkaMessageListenerContainer<String, String> container;
    private final CountDownLatch shutdownLatch = new CountDownLatch(1);

    public KafkaCompensationService(DataSource dataSource, String bootstrapServers) {
        this.dataSource = dataSource;
        this.kafkaTemplate = createKafkaTemplate(bootstrapServers);
        this.container = createContainer(bootstrapServers);
        this.container.start();
    }

    /**
     * 发送补偿消息
     */
    public void scheduleCompensation(String transactionId, int delaySeconds) {
        try {
            // 发送延迟消息
            kafkaTemplate.send(TOPIC, transactionId);
            log.info("已发送补偿消息: {}", transactionId);
        } catch (Exception e) {
            log.error("发送补偿消息失败: {}", transactionId, e);
            // 记录到补偿表，后续由定时任务处理
            recordFailedCompensation(transactionId, e);
        }
    }

    private void handleCompensationMessage(String transactionId) {
        try {
            // 1. 检查是否需要补偿
            if (!needCompensation(transactionId)) {
                return;
            }

            // 2. 获取事务记录
            TransferRecord record = getTransferRecord(transactionId);
            if (record == null) {
                log.warn("找不到事务记录: {}", transactionId);
                return;
            }

            // 3. 执行补偿
            compensateTransaction(record);

        } catch (Exception e) {
            log.error("处理补偿消息失败: {}", transactionId, e);
            recordFailedCompensation(transactionId, e);
        }
    }

    private boolean needCompensation(String transactionId) {
        String sql = "SELECT status FROM transfer_record WHERE transaction_id = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, transactionId);
            ResultSet rs = pstmt.executeQuery();

            return rs.next() && "TRYING".equals(rs.getString("status"));
        } catch (SQLException e) {
            log.error("检查补偿状态失败", e);
            return false;
        }
    }

    private TransferRecord getTransferRecord(String transactionId) {
        String sql = "SELECT * FROM transfer_record WHERE transaction_id = ? FOR UPDATE";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, transactionId);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                TransferRecord record = new TransferRecord();
                record.setId(rs.getLong("id"));
                record.setTransactionId(rs.getString("transaction_id"));
                record.setFromUserId(rs.getString("from_user_id"));
                record.setToUserId(rs.getString("to_user_id"));
                record.setAmount(rs.getBigDecimal("amount"));
                record.setStatus(rs.getString("status"));
                record.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
                return record;
            }
        } catch (SQLException e) {
            log.error("获取事务记录失败", e);
        }
        return null;
    }

    private void compensateTransaction(TransferRecord record) {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            conn.setAutoCommit(false);

            // 1. 解冻转出账户金额
            String updateFromAccountSql =
                "UPDATE account SET balance = balance + ?, freeze_amount = freeze_amount - ? " +
                "WHERE user_id = ? AND freeze_amount >= ?";

            try (PreparedStatement pstmt = conn.prepareStatement(updateFromAccountSql)) {
                pstmt.setBigDecimal(1, record.getAmount());
                pstmt.setBigDecimal(2, record.getAmount());
                pstmt.setString(3, record.getFromUserId());
                pstmt.setBigDecimal(4, record.getAmount());

                int updated = pstmt.executeUpdate();
                if (updated != 1) {
                    throw new BusinessException("COMP-002", "解冻金额失败");
                }
            }

            // 2. 更新转账记录状态
            String updateRecordSql =
                "UPDATE transfer_record SET status = 'CANCELLED', update_time = ? " +
                "WHERE transaction_id = ? AND status = 'TRYING'";

            try (PreparedStatement pstmt = conn.prepareStatement(updateRecordSql)) {
                pstmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
                pstmt.setString(2, record.getTransactionId());

                int updated = pstmt.executeUpdate();
                if (updated != 1) {
                    throw new BusinessException("COMP-003", "更新转账记录状态失败");
                }
            }

            // 3. 记录补偿成功
            recordSuccessfulCompensation(conn, record);

            conn.commit();
            log.info("成功补偿事务: {}", record.getTransactionId());

        } catch (Exception e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    log.error("回滚失败", ex);
                }
            }
            throw new BusinessException("COMP-004", "补偿事务失败: " + e.getMessage());
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("关闭连接失败", e);
                }
            }
        }
    }

    private void recordSuccessfulCompensation(Connection conn, TransferRecord record) throws SQLException {
        String sql = "INSERT INTO compensation_record " +
                    "(transaction_id, status, create_time) VALUES (?, 'SUCCESS', ?)";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, record.getTransactionId());
            pstmt.setTimestamp(2, Timestamp.valueOf(LocalDateTime.now()));
            pstmt.executeUpdate();
        }
    }

    private void recordFailedCompensation(String transactionId, Exception e) {
        String sql = "INSERT INTO compensation_record " +
                    "(transaction_id, status, error_message, retry_count, next_retry_time) " +
                    "VALUES (?, 'FAILED', ?, ?, ?)";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            LocalDateTime nextRetryTime = LocalDateTime.now().plusMinutes(1);

            pstmt.setString(1, transactionId);
            pstmt.setString(2, e.getMessage());
            pstmt.setInt(3, 0);
            pstmt.setTimestamp(4, Timestamp.valueOf(nextRetryTime));

            pstmt.executeUpdate();
        } catch (SQLException ex) {
            log.error("记录失败补偿异常", ex);
        }
    }

    private KafkaTemplate<String, String> createKafkaTemplate(String bootstrapServers) {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        ProducerFactory<String, String> producerFactory = new DefaultKafkaProducerFactory<>(props);
        return new KafkaTemplate<>(producerFactory);
    }

    private KafkaMessageListenerContainer<String, String> createContainer(String bootstrapServers) {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "tcc-compensation-group");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

        ConsumerFactory<String, String> consumerFactory = new DefaultKafkaConsumerFactory<>(props);

        ContainerProperties containerProps = new ContainerProperties(TOPIC);
        containerProps.setMessageListener((MessageListener<String, String>) record ->
            handleCompensationMessage(record.value()));

        return new KafkaMessageListenerContainer<>(consumerFactory, containerProps);
    }

    public void shutdown() {
        container.stop();
        shutdownLatch.countDown();
    }

    public void setKafkaTemplate(KafkaTemplate<String, String> kafkaTemplate) {
    }

    public void setAccountService(AccountService accountService) {
    }
}
